﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace DIProject.Sales
{
	public partial class CashOperation : Form
	{	
        public	int CashRegisterShiftId
        {
            get
            {
                return cashRegisterShiftId;
            }
        }
		private	int cashRegisterShiftId = 0;

		public	string CashRegisterName
        {
            get
            {
                return cashRegisterName;
            }
        }
		private	string cashRegisterName = string.Empty;

		public virtual decimal Sum
        {
            get
            {
                return 0m;
            }
        }

	/// <summary>Идентификатор возвращаемого документа. Требуется для возврата чека</summary>
		protected	int?		contragentDocId		= null;
	/// <summary>Дата возвращаемого документа. Требуется для возврата чека</summary>
		protected	DateTime?	contragentDocDate	= null;
	/// <summary>Номер возвращаемого документа. Требуется для возврата чека</summary>
		protected	string		contragentDocNumber	= null;

		public	DIProject.DataSets.Sales.GoodsSearchRow SearchedGoodsRow
		{	
            get
            {	
                return	searchedGoods.CurrentCell != null
					?	(DIProject.DataSets.Sales.GoodsSearchRow)((DataRowView)searchedGoods.CurrentCell.OwningRow.DataBoundItem).Row
					:	null
					;
			}
		}
        /// <summary>
        /// 
        /// </summary>
		protected bool modified = false;
		private ToolStripMenuItem ownerItem = null;

		private CashOperation() : this(null)	// Для дизайнера
		{
		}

		protected CashOperation(ToolStripMenuItem ownerItem)
		{	
            InitializeComponent();
			this.ownerItem = ownerItem;
			if(ownerItem != null)
			{	
                ownerItem.OwnerItem.Tag = (int)ownerItem.OwnerItem.Tag + 1;
				cashRegisterShiftId	= (int)ownerItem.Tag;
				cashRegisterName	= ownerItem.Text;
				ownerItem.Tag		= this;
			}
		}

		protected override void OnFormClosed(FormClosedEventArgs e)
		{	
            base.OnFormClosed(e);
			if(ownerItem != null)
			{	ownerItem.Tag = cashRegisterShiftId;
				ownerItem.OwnerItem.Tag = (int)ownerItem.OwnerItem.Tag - 1;
			}
		}

		protected string TextFormat{get{return textFormat;}}
		private string textFormat = string.Empty;

		protected virtual void SetCaption()
		{
		}

		protected override void OnLoad(EventArgs e)
		{	textFormat = Text;

			base.OnLoad(e);

			changeColWidth = false;
			SetCaption();
		}

		private void CashOperation_FormClosing(object sender, FormClosingEventArgs e)
		{	if(modified)
			{	switch
				(	MessageBox.Show
					(	this
					,	Properties.Resources.strClosingCashCheck
					,	Properties.Resources.strConfirmation
					,	MessageBoxButtons.YesNoCancel
					,	MessageBoxIcon.Question
					,	MessageBoxDefaultButton.Button1
					)
				)
				{	case DialogResult.Yes:	CloseNewDoc();	break;	// закрыть
					case DialogResult.No:	CancelNewDoc();	break;	// отменить
				}
				if(modified)			// всё ещё модифицирован
					e.Cancel = true;	// окно не закрываем
			}
		}
//-------------------------------------------------------------------------------------------------
// Операции с документом
		protected virtual void CreateNewDoc()
		{
		}

		protected virtual void RefreshDoc()
		{
		}

		protected virtual void CloseNewDoc()
		{
		}

		protected virtual void CancelNewDoc()
		{
		}
//-------------------------------------------------------------------------------------------------
// Операции со строками документа
		protected virtual bool LineInsert()
		{	return false;
		}

		protected virtual bool LineUpdate(int rowIndex)
		{	return false;
		}
//-------------------------------------------------------------------------------------------------
// Синхронизация ширин колонок обоих гридов
		private bool changeColWidth = true;	// признак режима автоматического изменения ширины колонки (см. CashSales_Load)
		private void cashRegisterLines_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)
		{	if(!changeColWidth													// не автоматическое изменение ширины
			&& e.Column != retailSumDataGridViewTextBoxColumn)					//  и не колонка "Сумма"
			{	changeColWidth = true;											// выставляем признак
				searchedGoods.Columns[e.Column.Index].Width = e.Column.Width;
				changeColWidth = false;											// снимаем признак
			}
		}

		private void searchedGoods_ColumnWidthChanged(object sender, DataGridViewColumnEventArgs e)
		{	if(!changeColWidth)													// не автоматическое изменение ширины
			{	changeColWidth = true;											// выставляем признак
				cashRegisterLines.Columns[e.Column.Index].Width = e.Column.Width;
				changeColWidth = false;											// снимаем признак
			}
		}
//-------------------------------------------------------------------------------------------------
		private DataGridViewCell lastCurrentCell = null;
		private void searchedGoods_CurrentCellChanged(object sender, EventArgs e)
		{	DataGridViewCell currentCell = searchedGoods.CurrentCell;
			if(currentCell != null && (lastCurrentCell == null || lastCurrentCell.RowIndex != currentCell.RowIndex))
			{	textBoxName.Text	= SearchedGoodsRow.Name;
				textBoxBarcode.Text	= SearchedGoodsRow.Barcode;
			}
			lastCurrentCell = currentCell;
		}
//-------------------------------------------------------------------------------------------------
		private void textBox_Enter(object sender, EventArgs e)
		{	(sender as TextBox).SelectAll();
		}

		private Control focusedControl = null;
		private void textBoxQntty_Leave(object sender, EventArgs e)
		{	focusedControl = null;
		}
//-------------------------------------------------------------------------------------------------
		private void textBoxQntty_KeyPress(object sender, KeyPressEventArgs e)
		{	switch(e.KeyChar)
			{	case '\b':	break;
				case '\r':	if(focusedControl != null)
								focusedControl.Focus();
							break;
				default:	if(!char.IsDigit(e.KeyChar))	// Не цифра
							{	Console.Beep();
								e.Handled = true;
							}
							break;
			}
		}

		private void textBoxBarcode_KeyPress(object sender, KeyPressEventArgs e)
            {
            if (e.KeyChar == '\r')
                {
                focusedControl = textBoxBarcode;
                // Поиск товара по штрих-коду
                try
                    {
                    goodsSearchTableAdapter.Fill(sales.GoodsSearch, contragentDocId, textBoxBarcode.Text, null);
                    if (sales.GoodsSearch.Count > 0)
                        {
                        searchedGoods.CurrentCell = searchedGoods.Rows[0].Cells[searchedGoods.CurrentCell.ColumnIndex];
                        if (LineInsert())			// Вставка строки в чек
                            textBoxQntty.Text = "1";
                        }
                    else
                        {
                        textBoxName.Text = string.Empty;
                        Console.Beep();
                        }
                    }
                catch (SqlException eq)
                    {
                    MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                catch (Exception ex)
                    {
                    MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            else
            {
                e.Handled = true;
                
            }
		}

		private void textBoxName_KeyPress(object sender, KeyPressEventArgs e)
		{	if(e.KeyChar == '\r')
			{	focusedControl = textBoxName;
			// Поиск товара по наименованию
				try
				{	
                    goodsSearchTableAdapter.Fill(sales.GoodsSearch,contragentDocId, null,  textBoxName.Text + "%");
					if(sales.GoodsSearch.Count > 0)
					{	
                        searchedGoods.CurrentCell = searchedGoods.Rows[0].Cells[searchedGoods.CurrentCell.ColumnIndex];
						searchedGoods.Focus();
					}
					else
					{	
                        textBoxBarcode.Text = string.Empty;
						Console.Beep();
					}
				}
				catch(SqlException eq)
				{	
                    MessageBox.Show(this, string.Format("{0} ({1}): {2}", eq.Procedure, eq.LineNumber, eq.Message), Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
				catch(Exception ex)
				{	
                    MessageBox.Show(this, ex.Message, Properties.Resources.strError, MessageBoxButtons.OK, MessageBoxIcon.Error);
				}
			}
		}
        protected virtual void DivGood(DataSets.Sales.GoodsSearchRow row)
        { }
		private void searchedGoods_KeyDown(object sender, KeyEventArgs e)
		{
            if (e.KeyCode == Keys.F11)
            {
                if (searchedGoods.SelectedRows.Count == 1)
                {
                    DataRowView drv = searchedGoods.SelectedRows[0].DataBoundItem as DataRowView;
                    if (drv != null)
                    {
                        DataSets.Sales.GoodsSearchRow rw = drv.Row as DataSets.Sales.GoodsSearchRow;
                        if (rw != null)
                        {
                            DivGood(rw);
                            return;
                        }
                    }
                }                    
            }
            if(e.KeyCode == Keys.Enter)
			{	if(LineInsert())			// Вставка строки в чек
				{	textBoxQntty.Text = "1";
					textBoxName.Focus();
				}
				e.Handled = true;			// Предотвращаем перемещение текущей строки грида на следующую
			}
		}

		private void searchedGoods_MouseDoubleClick(object sender, MouseEventArgs e)
		{	DataGridView.HitTestInfo hit = searchedGoods.HitTest(e.X, e.Y);
			if(hit.RowIndex >= 0)
			{	if(LineInsert())			// Вставка строки в чек
				{	textBoxQntty.Text = "1";
					textBoxName.Focus();
				}
			}
		}
//-------------------------------------------------------------------------------------------------
		/// <summary>
		/// обновляем документ
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="e"></param>
        private void toolStripButtonRefresh_Click(object sender, EventArgs e)
		{	RefreshDoc();
		}
        /// <summary>
        /// создаем новый чек
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
		protected void toolStripButtonCreate_Click(object sender, EventArgs e)
		{	
            if(toolStripButtonCreate.Enabled)
                CreateNewDoc();
            //RefreshDoc();
		}

		private void toolStripButtonClose_Click(object sender, EventArgs e)
		{
            if(toolStripButtonCreate.Enabled)
            {
                MessageBox.Show("Нет открытого чека","Откройте чек",MessageBoxButtons.OK,MessageBoxIcon.Warning);
                return;
            }
            if(Sum > 0m)
				CloseNewDoc();
		}

		private void toolStripButtonCancel_Click(object sender, EventArgs e)
		{	CancelNewDoc();
		}
//-------------------------------------------------------------------------------------------------
		private void cashRegisterLines_CellValueChanged(object sender, DataGridViewCellEventArgs e)
		{	
            if(e.RowIndex >= 0)
				LineUpdate(e.RowIndex);
		}

        private void CashOperation_KeyDown(object sender, KeyEventArgs e)
        {
            //Открыть чек
            if (e.KeyCode == Keys.F3)
            {
                this.toolStripButtonCreate_Click(this.toolStripButtonCreate, EventArgs.Empty);
            }
            //закрыть чек
            if (e.KeyCode == Keys.F9)
            {
                this.toolStripButtonClose_Click(toolStripButtonClose, EventArgs.Empty);
            }
            //обновить
            if (e.KeyCode == Keys.F12)
            {
                RefreshDoc();
            }
            //Подбор товара по прайс листу
            if (e.KeyCode == Keys.F2)
            {
                textBoxName.Text = string.Empty;
                textBoxName.Focus();
            }
            //Изменить количество товара в чеке
            if (e.KeyCode == Keys.F5)
            {
                textBoxQntty.Focus();
            }
            //перейти к выбранным товарам
            if (e.KeyCode == Keys.F8)
            {
                cashRegisterLines.Focus();
                if (cashRegisterLines.Rows.Count > 0)
                    cashRegisterLines.Rows[0].Selected = true;
            }
            //перейти к выбираемым товарам
            if (e.KeyCode == Keys.F7)
            {
                searchedGoods.Focus();
                if (searchedGoods.Rows.Count > 0)
                {
                    searchedGoods.Rows[0].Selected = true;
                }
            }
        
        }
        private void DoBarCodeInput(string barCode)
        {
            textBoxBarcode.Text = barCode;
            textBoxBarcode.Focus();
            //SendKeys.Send("\r");
        }
        protected string buffer = string.Empty;
        public virtual void GetChek(){}
        private void toolStripButton1_Click(object sender, EventArgs e)
            {
            GetChek();
            }

        private void CashOperation_FormClosed(object sender, FormClosedEventArgs e)
        {
            
        }

        private void textBoxBarcode_Leave(object sender, EventArgs e)
            {
            textBoxBarcode.Text = string.Empty;
            buffer = string.Empty;
            }

        private void CashOperation_KeyPress(object sender, KeyPressEventArgs e)
            {
            char tmp = e.KeyChar;
            if (char.IsDigit(tmp))
                {
                
                    buffer += tmp;
                    if (buffer.Length == 13)
                        {
                        DoBarCodeInput(buffer);
                        buffer = string.Empty;
                        e.Handled = true;
                        }
                    
                }
            else
                {
                if(e.KeyChar!='\r')
                    buffer = string.Empty;
                }
            //e.Handled = true;
            }

        private void textBoxQntty_TextChanged(object sender, EventArgs e)
            {
            string str = textBoxQntty.Text;
            if (string.IsNullOrEmpty(str))
            {
            textBoxQntty.Text = "1";
            return;
                }
            if (str.Length > 3)
            {
            textBoxQntty.Text = "1";
            return;
                }
            Int32 tmp;
            if (!Int32.TryParse(str, out tmp))
            {
            textBoxQntty.Text = "1";
            return;
                }
            }

        private void textBoxBarcode_TextChanged(object sender, EventArgs e)
            {
            textBoxQntty.Text = "1";
            buffer = string.Empty;
            }

        private void ContinuePrintToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Util.CashRecorder.GetECRStatus();
            if (Util.CashRecorder.ResultCode == 3)
            {
                Util.CashRecorder.ContinuePrint();
            }
        }
//-------------------------------------------------------------------------------------------------
	}
}